package com.example.rdb.utils;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @Version 1.0
 * @Author:徐衍程
 * @Date:2021/8/22
 * @Content:
 */
@Slf4j
public class JsonUtils {

    public static String readJsonFile(File jsonFile) {
        String jsonStr = "";
        log.info("————开始读取" + jsonFile.getPath() + "文件————");
        FileReader fileReader = null;
        Reader reader = null;
        try {
            //File jsonFile = new File(fileName);
            fileReader = new FileReader(jsonFile);
            reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            jsonStr = sb.toString();
            log.info("————读取" + jsonFile.getPath() + "文件结束!————");
            return jsonStr;
        } catch (Exception e) {
            log.info("————读取" + jsonFile.getPath() + "文件出现异常，读取失败!————");
            e.printStackTrace();
            return null;
        }finally {
            try {
                fileReader.close();
                reader.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    public static JSONArray jsonStrToArray(String table,String json){
        String jsonStr = JsonUtils.readJsonFile(new File(table+".json"));
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        JSONArray jsonArray = (JSONArray) jsonObject.get("RECORDS");
        return jsonArray;
    }

    public static String getType(Object object){
        String typeName=object.getClass().getName();
        int length= typeName.lastIndexOf(".");
        String type =typeName.substring(length+1);
        return type;
    }

}
